/* Includes ------------------------------------------------------------------*/
#include "stm32f10x_flash.h"
#include "stmflash.h"
#include "stdio.h"
#include "string.h"
#include "global.h"


uint8_t DFlashRWBlock(uint32 dwAddr, uint8*cpBuffer, uint32 dwCount, uint8 cType)
{
	uint32_t i,j, Address = 0,flag = 0;
	u16 tmpWord;
	FLASH_Status FLASHStatus;
	uint32_t NbrOfPage = 0x00;
	uint32_t EraseCounter = 0x00;
	unsigned char Start_Ease_Page,End_Ease_Page=0;
	if(cType==WRITEMODE)
	{
		FLASHStatus = FLASH_COMPLETE;

		FLASH_Unlock();

		Start_Ease_Page=(dwAddr-0x08000000)/ FLASH_PAGE_SIZE;	

		End_Ease_Page=(dwAddr+dwCount-0x08000000)/ FLASH_PAGE_SIZE;
		NbrOfPage =End_Ease_Page-Start_Ease_Page; 

		FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);	

		for(EraseCounter = 0; (EraseCounter <=NbrOfPage) && (FLASHStatus == FLASH_COMPLETE); EraseCounter++)
		{
			FLASHStatus = FLASH_ErasePage(0x08000000+(Start_Ease_Page*FLASH_PAGE_SIZE) + (FLASH_PAGE_SIZE * EraseCounter));
		}

		Address = dwAddr;
		if(dwCount%2 == 1)
		{
			dwCount = dwCount - 1;
			flag = 1;
		}
		for(i=0,j=0;(i<dwCount) && (FLASHStatus == FLASH_COMPLETE);i+=2)
		{
			tmpWord = cpBuffer[j+1]<<8 | cpBuffer[j];
			FLASHStatus = FLASH_ProgramHalfWord(Address+i,tmpWord);
			j+=2;
		}

		if(flag == 1)
		{
			tmpWord = 0xFF & cpBuffer[dwCount];
			FLASH_ProgramHalfWord(Address+i,tmpWord);
		}
		
   		return 0x00;
	}	
	if(cType==READMODE)		
	{
		FLASH_Unlock();
		Address = dwAddr;
		FLASHStatus = FLASH_COMPLETE;
		for(i=0,j=0;(i< dwCount) && (FLASHStatus == FLASH_COMPLETE);i++)
		{
			cpBuffer[i] = *(volatile unsigned char *)(Address++);
		}
	   	return 0x00;
	}
   	return 0x00;
}

 
 
